package com.qzdin.armface.action;
import cn.smartjavaai.common.entity.DetectionInfo;
import cn.smartjavaai.common.entity.DetectionResponse;
import cn.smartjavaai.common.entity.R;
import cn.smartjavaai.common.entity.face.FaceInfo;
import cn.smartjavaai.face.enums.SimilarityType;
import cn.smartjavaai.face.model.facerec.FaceRecModel;
import cn.smartjavaai.face.utils.SimilarityUtil;
import com.qzdin.armface.service.CoreService;
import com.qzdin.armface.util.ThermalData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * @author : maxiaojie
 * @data : 2025/8/14 10:51
 */
@RestController
public class CommonAction {

    @Autowired
    private CoreService service;

    /**
     * 预注册-热数据
     */
    public static List<ThermalData> THERMAL_DATA = new ArrayList<>();

    /**
     * 对比两个人脸的相似度
     * @param imgUrlA
     * @param imgUrlB
     * @param type
     * @return
     */
    @RequestMapping(value = "public/facialComparison")
    public Object facialComparison(@RequestParam String imgUrlA,@RequestParam String imgUrlB,@RequestParam(required = false, defaultValue = "1") Integer type) {
        //根据 图片url 获取 二进制
        float result = 0f;
        byte[] bytesA = null;
        if(StringUtils.isNotBlank(imgUrlA)) {
            try {
                bytesA = downloadImage(imgUrlA);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        byte[] bytesB = null;
        if(StringUtils.isNotBlank(imgUrlB)) {
            try {
                bytesB = downloadImage(imgUrlB);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(bytesA != null && bytesB != null) {
            try {
                //高精度模型，速度慢, 追求速度请更换高速模型: getHighSpeedFaceRecModel
                FaceRecModel faceRecModel = service.getHighSpeedFaceRecModel();
                //基于图像直接比对人脸特征
                R<Float> similarResult = faceRecModel.featureComparison(bytesA, bytesB);
                if(similarResult.isSuccess()){
                    if(similarResult.getData() != null) {
                        result = similarResult.getData();
                    }
                }else{
                    System.out.println("人脸比对失败："+similarResult.getMessage());
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 预注册-网络资源
     * @param imgUrl
     * @return
     */
    @RequestMapping(value = "public/preRegistrationUrl")
    public Object preRegistrationUrl(@RequestParam String nickName,@RequestParam String imgUrl) {

        if(StringUtils.isBlank(imgUrl)) {
            return 405;
        }
        byte[] bytesA = null;
        try {
            bytesA = downloadImage(imgUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(bytesA == null) {
            return 500;
        }
        try {
            FaceRecModel faceRecModel = service.getHighSpeedFaceRecModel();
            BufferedImage bufferedImage1 = ImageIO.read(new ByteArrayInputStream(bytesA));
            R<float[]> feature1 = faceRecModel.extractTopFaceFeature(bufferedImage1);
            float[] data = feature1.getData();
            if(data != null) {
                THERMAL_DATA.add(new ThermalData(nickName.trim(),data));
            }
            System.out.println("热数据:"+THERMAL_DATA.size());
        } catch (IOException e) {
            return 500;
        }

        return 200;
    }

    /**
     * 从热数据中检索
     * @param imgUrl
     * @return
     */
    @RequestMapping(value = "public/facialComparisonHot")
    public Object facialComparisonHot(@RequestParam String imgUrl) {
        Map<String,Object> result = new HashMap<>();
        int code = 200;
        if(THERMAL_DATA.size() == 0) {
            code = 405;
            result.put("code",code);
            return result;
        }
        if(StringUtils.isBlank(imgUrl)) {
            code = 405;
            result.put("code",code);
            return result;
        }
        byte[] bytesA = null;
        try {
            bytesA = downloadImage(imgUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(bytesA == null) {
            code = 500;
            result.put("code",code);
            return result;
        }
        FaceRecModel faceRecModel = service.getHighSpeedFaceRecModel();
        R<DetectionResponse> detectionResponseR = faceRecModel.extractFeatures(bytesA);
        if(detectionResponseR.isSuccess()){
            List<String> names = new ArrayList<>();
            DetectionResponse detectionResponse = detectionResponseR.getData();
            if(detectionResponse != null && detectionResponse.getDetectionInfoList() != null && detectionResponse.getDetectionInfoList().size() > 0) {
                for(DetectionInfo detectionInfo : detectionResponse.getDetectionInfoList()) {
                    FaceInfo faceInfo = detectionInfo.getFaceInfo();
                    if(faceInfo != null) {
                        float[] feature = faceInfo.getFeature();
                        for(ThermalData thermalData : THERMAL_DATA) {
                            float calculate = SimilarityUtil.calculate(feature, thermalData.getData(), SimilarityType.IP, true);
                            if(calculate > 0.75) {
                                if(!names.contains(thermalData.getNickName())) {
                                    names.add(thermalData.getNickName());
                                }
                            }
                        }
                    }
                }
            }
            if(names.size() > 0) {
                result.put("names",names);
            }
        }
        return result;
    }


    public static byte[] downloadImage(String imageUrl) throws Exception {
        URL url = new URL(imageUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000); // 5秒连接超时
        conn.setReadTimeout(15000);   // 10秒读取超时

        try (InputStream inStream = conn.getInputStream();
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

            byte[] buffer = new byte[4096];
            int len;
            while ((len = inStream.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            return baos.toByteArray();
        } finally {
            conn.disconnect(); // 确保关闭连接
        }
    }

}
